package im.push.impush.wspush.wss;

import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.yeauty.annotation.*;
import org.yeauty.pojo.Session;

import java.io.IOException;

/**
 * @author ccl
 * @time 2018-11-01 13:51
 * @name WebSockerServer
 * @desc:
 */
@ServerEndpoint(prefix = "oim")
@Component
@Slf4j
public class WebSockerServer {
    @OnOpen
    public void onOpen(Session session, HttpHeaders headers) throws IOException {
        String remoteAddress = getRemoteAddress(session);
        log.info("{} ---> connected", remoteAddress);
    }

    @OnClose
    public void onClose(Session session) throws IOException {
        String remoteAddress = getRemoteAddress(session);
        log.info("{} ---> disconnected", remoteAddress);
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        throwable.printStackTrace();
    }

    @OnMessage
    public void OnMessage(Session session, String message) {
        String remoteAddress = getRemoteAddress(session);
        log.info("{} send message: {}", remoteAddress, message);
        session.sendText("Hello Netty!");
    }

    @OnBinary
    public void OnBinary(Session session, byte[] bytes) {
        for (byte b : bytes) {
            System.out.println(b);
        }
        session.sendBinary(bytes);
    }

    @OnEvent
    public void onEvent(Session session, Object evt) {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
            switch (idleStateEvent.state()) {
                case READER_IDLE:
                    log.info("read idle");
                    break;
                case WRITER_IDLE:
                    log.info("write idle");
                    break;
                case ALL_IDLE:
                    log.info("all idle");
                    break;
                default:
                    break;
            }
        }
    }

    private String getRemoteAddress(Session session){
       return session.channel().remoteAddress().toString();
    }
}
